<?php
defined('CITY_BAO') or exit('Access Denied');
require CB_CORE.'modules/'.$config_module['module'].'/common.inc.php';
if($user->userid>0) redirect(INSTALL_PATH.'member/');
$forward = $request->getParam('forward');
if(!$forward) {
	$reffer = $request->getReffer();
	$forward = $reffer?$reffer:SITE_URL;
	if(strpos($forward,'member/login')){
		$forward = SITE_URL;
	}
}
$captcha_login = isset($config_member['captcha_login'])?$config_member['captcha_login']:1;
$login_ajax = isset($config_member['login_ajax'])?$config_member['login_ajax']:0;
$form_validate = form_validate('login');
$flag = true;
$error = '';
if($request->isPost()){
	$validate = trim($request->getParam('validate'));
	if($validate != $form_validate){
		$error = '数据来源校验失败！';
		$flag = false;
	}
	if($flag&&$captcha_login){
		$captcha = trim($request->getParam('captcha'));
		if(!isset($_SESSION['AuthCode'])){
			$error = '验证码已过期！';
			$flag = false;
		}elseif(md5($captcha) != $_SESSION['AuthCode']){
			$error = '验证码输入错误！';
			$flag = false;
		}
		unset($_SESSION['AuthCode']);
	}
	$username = trim($request->getParam('username'));
	if($flag){
		$password = trim($request->getParam('password'));
		$remember = trim($request->getParam('remember'),0);
		if(!$username){
			$error = '请输入用户名！';
			$flag = false;
		}elseif(!$password){
			$error = '请输入密码！';
			$flag = false;
		}
		if($flag){
			$cookie_time = 60*60*24*$remember;
			$user = $cbdb->get_row("SELECT * FROM {#cbdbPrefix}members WHERE username='".$username."' AND password='".md5($password)."' LIMIT 0,1");
			if($user){
				if(isset($config_member['log_user_login'])&&$config_member['log_user_login']){
					$logger->log("{$username}于".date('Y-m-d H:i:s',TIME_STAMP)."在".IP_ADDRESS."处登录了。",'user_login',$username);
				}
				set_cookie('auth_user',$user,$cookie_time);
				$user->credit+= intval($config_member['credit_login']);
				$user->logintimes+= 1;
				$cbdb->query("UPDATE {#cbdbPrefix}members SET credit='{$user->credit}',last_logintime='".TIME_STAMP."',last_loginip='".IP_ADDRESS."',logintimes='{$user->logintimes}' WHERE userid=".$user->userid);
			}else{
				$error = '用户名或密码错误！';
				$flag = false;
			}
		}
	}
	if($flag){
		if($request->isXmlHttpRequest()){
			exit('yes:'.$forward);
		}else{
			redirect($forward);
		}
	}else{
		if($request->isXmlHttpRequest()){
			exit('no:'.$error);
		}else{
			$tpl->assign('error',$error);
			$tpl->assign('username',$username);
		}
	}
}
$tpl->assign('forward',$forward);
$tpl->assign('validate',$form_validate);
$tpl->assign('captcha_login',$captcha_login);
$tpl->assign('login_ajax',$login_ajax);
$tpl->assign('title','用户登录');
$tpl->display('member/login.tpl');